// 基于 SnowLang Project (https://gitee.com/jcnc-org/snow) 的衍生作品
// 原始版权归属: Copyright © 2025 Ke Xu (Luke)
// 本实现版权归属: Copyright © 2025 Sany
// 遵循 Apache License 2.0 授权
package control

import (
	"errors"
	"strconv"

	"gitee.com/xntk2381/cc/vm/module"
)

type IIncCommand struct{}

func (IIncCommand) Execute(parts []string, currentPC int, operandStack *module.OperandStack, localVariableStore *module.LocalVariableStore, callStack *module.CallStack) (int, error) {
	if len(parts) < 2 {
		return 0, errors.New("no target command address specified for IINC operation")
	}
	localVariableIndex, err := strconv.Atoi(parts[1])
	if err != nil {
		return 0, errors.New("invalid target command address specified for IINC operation")
	}

	incrementValueI, err := strconv.Atoi(parts[2])
	if err != nil {
		return 0, errors.New("invalid increment value specified for IINC operation")
	}
	incrementValue := int32(incrementValueI)

	frm, err := callStack.PeekFrame()
	if err != nil {
		return 0, err
	}

	currentValueI, err := frm.GetLocalVariableStore().GetVariable(localVariableIndex)
	if err != nil {
		return 0, err
	}
	currentValue := currentValueI.(int32)
	frm.GetLocalVariableStore().SetVariable(localVariableIndex, currentValue+incrementValue)
	return currentPC + 1, nil
}
